const express = require('express')
const Axios = require('axios')
const router = express.Router()
const db = require('../db/mysql')
const CryptoJS = require('crypto-js')
const multer = require('multer')
const uuid = require("uuid")


// 指定存储位置
const storage = multer.diskStorage({
  // 存储位置
  destination(req, file, callback) {
    // 参数一 错误信息   参数二  上传路径（此处指定upload文件夹）
    if(process.env.ENV == null){
      callback(null, "data/images")
    }else{
      callback(null, "../data/images")
    }
  },
  // 确定文件名
  filename(req, file, cb) {
    //文件扩展名
    let extName = file.originalname.slice(file.originalname.lastIndexOf('.'))
    //新文件名
    let fileName = uuid.v1()
    cb(null, fileName + extName)
  }
})
//上传中间件
const upload = multer({ storage })

//加密中间件
var checkToken = (req, res, next) => {
  // 解密
  try {
    const secretKey = process.env.API_SECRET_KEY // 密钥，需要和前端保持一致
    const ciphertext = req.body.data // 接收到的加密参数
    const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
      mode: CryptoJS.mode.ECB, // 模式
      padding: CryptoJS.pad.Pkcs7, // 填充
    }).toString(CryptoJS.enc.Utf8) // 明文
    const plaintext = decrypted
    const data = JSON.parse(plaintext)
    const timestamp = Date.now()
    if (Math.abs(data.timestamp - timestamp) > 10000) {
      res.status(400).send('请求超时')
    } else {
      req.data = data
      next()
    }
  } catch (e) {
    res.status(500).send('请求异常')
  }
}

/* GET home page. */
router.post('/addPrompt', checkToken, async function (req, res) {
  try {
    let prompt = req.data.prompt
    let userId = req.data.userId
    let addurl = req.data.addurl
    if (!userId || !prompt) {
      res.json({ msg: '参数错误' })
      return
    }
    let param = prompt
    if(addurl){
      param = addurl + ' ' + prompt
    }
    let config = sendConfigFirst(param)
    let res_send = await sendToDiscord(config)

    if (res_send) {
      let create_at = datetime()
      let sql =
        'insert into user_prompt_url set status = 1, type = 1, ispay = 1, user_id = "' +
        userId +
        '", prompt = "' +
        prompt +
        '", add_url = "' +
        addurl +
        '", create_at = "' +
        create_at +
        '", update_at = "' +
        create_at +
        '"'
      let response = await db.query(sql)
      if (response) {
        res.json({ code: 1, msg: '成功' })
      } else {
        res.json({ code: 0, msg: '失败' })
      }
    } else {
      res.json({ code: 0, msg: '发送失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/chooseDetail', checkToken, async function (req, res) {
  try {
    let prompt = req.data.prompt
    let userId = req.data.userId
    let messageId = req.data.messageId
    let num = req.data.num
    let messageName = req.data.messageName
    if (!userId || !prompt || !num || !messageName || !messageId) {
      res.json({ msg: '参数错误' })
      return
    }
    let config = sendConfigDetail(messageId, num, messageName)
    let res_send = await sendToDiscord(config)

    if (res_send) {
      let create_at = datetime()
      let sql =
        'insert into user_prompt_url set status = 1, type = 2, ispay = 1, user_id = "' +
        userId +
        '", prompt = "' +
        prompt +
        '", create_at = "' +
        create_at +
        '", update_at = "' +
        create_at +
        '"'
      let response = await db.query(sql)
      if (response) {
        res.json({ code: 1, msg: '成功' })
      } else {
        res.json({ code: 0, msg: '失败' })
      }
    } else {
      res.json({ code: 0, msg: '发送失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/chooseNew', checkToken, async function (req, res) {
  try {
    let prompt = req.data.prompt
    let userId = req.data.userId
    let messageId = req.data.messageId
    let num = req.data.num
    let messageName = req.data.messageName
    if (!userId || !prompt || !num || !messageName || !messageId) {
      res.json({ msg: '参数错误' })
      return
    }
    let config = sendConfigNew(messageId, num, messageName)
    let res_send = await sendToDiscord(config)

    if (res_send) {
      let create_at = datetime()
      let sql =
        'insert into user_prompt_url set status = 1, type = 1, ispay = 1, user_id = "' +
        userId +
        '", prompt = "' +
        prompt +
        '", create_at = "' +
        create_at +
        '", update_at = "' +
        create_at +
        '"'
      let response = await db.query(sql)
      if (response) {
        res.json({ code: 1, msg: '成功' })
      } else {
        res.json({ code: 0, msg: '失败' })
      }
    } else {
      res.json({ code: 0, msg: '发送失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/getPic', checkToken, async function (req, res) {
  try {
    let userId = req.data.userId
    if (!userId) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'select * from user_prompt_url where user_id = "' +
      userId +
      '" order by id desc limit 1'
    let response = await db.query(sql)
    if (response) {
      res.json({ data: response })
    } else {
      res.json({ msg: '查询失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/uploadImg', upload.single("file"), async function (req, res) {
  const src = process.env.DOMAIN + '/images/' + req.file.filename
  // console.log(req.file.filename);
  res.json({code: 1, src: src})
})

router.post('/getUserDoing', checkToken, async function (req, res) {
  try {
    let userId = req.data.userId
    let limit = req.data.limit
    let offset = req.data.offset
    if (!userId || !limit) {
      res.json({ msg: '参数错误' })
      return
    }
    let date = datetime(
      new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)
    )

    let sql =
      'select * from user_prompt_url where islost = 1 and ispay != 2 and ' +
      'create_at > "' +
      date +
      '" and ' +
      'user_id = "' +
      userId +
      '" order by update_at desc ' +
      'limit ' +
      limit +
      ' ' +
      'offset ' +
      offset
    let response = await db.query(sql)
    if (response) {
      res.json({ data: response })
    } else {
      res.json({ msg: '查询失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/getUserDoEnd', checkToken, async function (req, res) {
  try {
    let userId = req.data.userId
    let limit = req.data.limit
    let offset = req.data.offset
    if (!userId || !limit) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'select * from user_prompt_url where ispay = 2 and user_id = "' +
      userId +
      '" order by update_at desc ' +
      'limit ' +
      limit +
      ' ' +
      'offset ' +
      offset
    let response = await db.query(sql)
    if (response) {
      res.json({ data: response })
    } else {
      res.json({ msg: '查询失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/getLoopList', checkToken, async function (req, res) {
  try {
    let sql =
      'select id, ispay, order_no from user_prompt_url where ispay = 3 and order_no is not null'
    let response = await db.query(sql)
    if (response) {
      res.json({ data: response })
    } else {
      res.json({ msg: '查询失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/getIssetPic', checkToken, async function (req, res) {
  try {
    let userId = req.data.userId
    // let prompt = req.data.textareaValue
    if (!userId) {
      res.json({ msg: '参数错误' })
      return
    }
    let date = datetime(new Date(new Date().getTime() - 60 * 1000))

    let sql =
      'select count(0) as num from user_prompt_url where status = 1 and user_id = "' +
      userId +
      '" and create_at > "' +
      date +
      '"'
    let response = await db.query(sql)
    if (response) {
      res.json({ data: response })
    } else {
      res.json({ msg: '查询失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/picPay', checkToken, async function (req, res) {
  try {
    let userPromptUrlId = req.data.userPromptUrlId
    let ispay = req.data.ispay
    let update_at = datetime()
    if (!userPromptUrlId || !ispay) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'update user_prompt_url set ispay = '+ ispay +', update_at = "'+ update_at +'" where id = "' +
      userPromptUrlId +
      '"'
    let response = await db.query(sql)
    if (response) {
      res.json({ msg: '支付成功！' })
    } else {
      res.json({ msg: '操作失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/getPayStatus', checkToken, async function (req, res) {
  try {
    let userPromptUrlId = req.data.userPromptUrlId
    if (!userPromptUrlId) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'select ispay, order_no from user_prompt_url where id = "' +
      userPromptUrlId +
      '"'
    let response = await db.query(sql)
    if (response) {
      res.json({ msg: '成功', data: response })
    } else {
      res.json({ msg: '失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/saveOrderInfo', checkToken, async function (req, res) {
  try {
    let userPromptUrlId = req.data.userPromptUrlId
    let order_no = req.data.order_no
    if (!userPromptUrlId || !order_no) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'update user_prompt_url set order_no = "'+ order_no +'", ispay = 3 where id = "' +
      userPromptUrlId +
      '"'
    let response = await db.query(sql)
    if (response) {
      res.json({ msg: '成功' })
    } else {
      res.json({ msg: '失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

router.post('/setPicLost', checkToken, async function (req, res) {
  try {
    let userPromptUrlId = req.data.userPromptUrlId
    if (!userPromptUrlId) {
      res.json({ msg: '参数错误' })
      return
    }
    let sql =
      'update user_prompt_url set islost = 2 where id = "' +
      userPromptUrlId +
      '"'
    let response = await db.query(sql)
    if (response) {
      res.json({ msg: '操作成功！' })
    } else {
      res.json({ msg: '操作失败' })
    }
  } catch (error) {
    console.log(error)
    res.json({ error })
  }
})

async function sendToDiscord(config) {
  try {
    console.log('---------axios-start--------')
    const response = await Axios(config)
    console.log('---------axios-end----------')
    console.log(response.data)
    if (response.data == '') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}
function generateRandomNumber(n) {
  let result = ''
  for (let i = 0; i < n; i++) {
    result += Math.floor(Math.random() * 10)
  }
  return result
}
function datetime(datetime) {
  let date = ''
  if (datetime) {
    date = datetime
  } else {
    date = new Date()
  }
  const year = date.getFullYear()
  const month = padZero(date.getMonth() + 1) // JavaScript 中月份从 0 开始计数，所以需要加 1
  const day = padZero(date.getDate())
  const hour = padZero(date.getHours())
  const minute = padZero(date.getMinutes())
  const second = padZero(date.getSeconds())

  // 拼接成 MySQL DATETIME 格式的字符串并返回
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}
function padZero(num) {
  return num.toString().padStart(2, '0')
}
function sendConfigFirst(prompt) {
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
      authorization: process.env.DC_API_AUTH,
    },
    data: {
      type: 2,
      application_id: '936929561302675456',
      guild_id: '1077497600221126746',
      channel_id: '1077497600221126749',
      session_id: process.env.DC_API_SID,
      data: {
        version: process.env.DC_API_V,
        id: '938956540159881230',
        name: 'imagine',
        type: 1,
        options: [
          {
            type: 3,
            name: 'prompt',
            value: prompt,
          },
        ],
        application_command: {
          id: '938956540159881230',
          application_id: '936929561302675456',
          version: process.env.DC_API_V,
          //   default_permission: true,
          default_member_permissions: null,
          type: 1,
          nsfw: false,
          name: 'imagine',
          description: 'Create images with Midjourney',
          dm_permission: true,
          contexts: [0, 1, 2],
          options: [
            {
              type: 3,
              name: 'prompt',
              description: 'The prompt to imagine',
              required: true,
            },
          ],
        },
        attachments: [],
      },
      nonce: generateRandomNumber(20),
    },
  }
  return config
}

function sendConfigDetail(message_id, num, message_name) {
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
      authorization: process.env.DC_API_AUTH,
    },
    data: {
      type: 3,
      nonce: generateRandomNumber(20),
      guild_id: '1077497600221126746',
      channel_id: '1077497600221126749',
      message_flags: 0,
      message_id: message_id,
      application_id: '936929561302675456',
      session_id: process.env.DC_API_SID,
      data: {
        component_type: 2,
        custom_id: 'MJ::JOB::upsample::' + num + '::' + message_name,
      },
    },
  }
  return config
}

function sendConfigNew(message_id, num, message_name) {
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
      authorization: process.env.DC_API_AUTH,
    },
    data: {
      type: 3,
      nonce: generateRandomNumber(20),
      guild_id: '1077497600221126746',
      channel_id: '1077497600221126749',
      message_flags: 0,
      message_id: message_id,
      application_id: '936929561302675456',
      session_id: process.env.DC_API_SID,
      data: {
        component_type: 2,
        custom_id: 'MJ::JOB::variation::' + num + '::' + message_name,
      },
    },
  }
  return config
}

module.exports = router
